<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <div v-if="addEditFlag == 'edit'">
                <el-form-item :label="endPageData.dutyOne || '值班领导'">
                    <el-select v-model="ruleForm.leader" class="w100p" clearable multiple filterable placeholder="请选择">
                        <el-option v-for="item, index in staffList" :key="index" :label="item.personName"
                            :value="item.personName"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="endPageData.dutyTwo || '值班人员'">
                    <el-select v-model="ruleForm.officer" class="w100p" clearable multiple filterable placeholder="请选择">
                        <el-option v-for="item, index in staffList" :key="index" :label="item.personName"
                            :value="item.personName"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="endPageData.dutyThree || '值班驾驶员'">
                    <el-select v-model="ruleForm.driver" class="w100p" clearable multiple filterable placeholder="请选择">
                        <el-option v-for="item, index in staffList" :key="index" :label="item.personName"
                            :value="item.personName"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="值班日期" prop="dutyDate">
                    <el-date-picker class="w100p" v-model="ruleForm.dutyDate" type="date" value-format="yyyy-MM-dd"
                        placeholder="选择日期时间" :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
            </div>
            <div v-if="addEditFlag == 'add'">
                <template v-for="addInfo, addInfoIndex in ruleForm.addList">
                    <el-row class="elRowLine" :gutter="20">
                        <el-col :span="18">
                            <el-row :key="addInfoIndex">
                                <el-col :span="12">
                                    <el-form-item :label="endPageData.dutyOne || '值班领导'">
                                        <el-select v-model="addInfo.leader" class="w100p" clearable multiple filterable
                                            placeholder="请选择">
                                            <el-option v-for="item, index in staffList" :key="index"
                                                :label="item.personName" :value="item.personName"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item :label="endPageData.dutyTwo || '值班人员'">
                                        <el-select v-model="addInfo.officer" class="w100p" clearable multiple filterable
                                            placeholder="请选择">
                                            <el-option v-for="item, index in staffList" :key="index"
                                                :label="item.personName" :value="item.personName"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item :label="endPageData.dutyThree || '值班驾驶员'">
                                        <el-select v-model="addInfo.driver" class="w100p" clearable multiple filterable
                                            placeholder="请选择">
                                            <el-option v-for="item, index in staffList" :key="index"
                                                :label="item.personName" :value="item.personName"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="值班日期" :rules="rules.dutyDate"
                                        :prop="`addList[${addInfoIndex}][dutyDate]`">
                                        <el-date-picker class="w100p" v-model="addInfo.dutyDate" type="date"
                                            value-format="yyyy-MM-dd" placeholder="选择日期时间"
                                            :picker-options="pickerOptions">
                                        </el-date-picker>
                                    </el-form-item>
                                </el-col>
                            </el-row></el-col>
                        <el-col :span="6">
                            <el-button v-if="ruleForm.addList.length > 1" type="danger" icon="el-icon-delete" plain
                                @click="delList(addInfoIndex)">删
                                除</el-button>
                            <el-button v-if="addInfoIndex + 1 == ruleForm.addList.length" type="primary"
                                icon="el-icon-circle-plus-outline" plain @click="addList(addInfoIndex)">添加</el-button>
                        </el-col>
                    </el-row>

                </template>
            </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import UpLoadImage from "@/components/UpLoadImage";
import duty from "@/api/duty"
export default {
    components: { UpLoadImage },
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        endPageData: {
            type: Object,
            default: () => {
                return {}
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        staffList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7; //只能选择今天及今天之后的日期
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '明天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() + 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周后',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            resetImg: true,
            addEditName: '添加',
            addEditApi: '',
            fileIdList: [],
            ruleForm: {},
            rules: {
                dutyDate: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
                driver: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                officer: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                leader: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                filesId: [
                    { required: true, message: '请上传图片', trigger: 'change' }
                ],
                personName: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
            }
        }
    },
    computed: {

    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = duty.add
                this.addEditName = '添加';
                this.$set(this.ruleForm, 'addList', [
                    {
                        driver: [],
                        officer: [],
                        leader: [],
                        dutyDate: this.formatDate(new Date())
                    }
                ])
                this.addList(0);
                this.addList(1);
                this.addList(2);
                this.addList(3);
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.fileIdList = this.data.filesId ? [this.data.filesId] : [];
                this.addEditApi = duty.edit
                this.addEditName = '编辑'
                this.ruleForm.driver = this.ruleForm.driver ? this.ruleForm.driver.split(',') : [];
                this.ruleForm.officer = this.ruleForm.officer ? this.ruleForm.officer.split(',') : [];
                this.ruleForm.leader = this.ruleForm.leader ? this.ruleForm.leader.split(',') : [];
            }
        },
        getNextDay(date) {
            const nextDay = new Date(date.getTime());
            nextDay.setDate(date.getDate() + 1);
            return nextDay;
        },
        formatDate(date, includeTime = false) {
            const yyyy = date.getFullYear();
            const MM = (date.getMonth() + 1).toString().padStart(2, '0');
            const dd = date.getDate().toString().padStart(2, '0');

            let formattedDate = `${yyyy}-${MM}-${dd}`;

            if (includeTime) {
                const HH = date.getHours().toString().padStart(2, '0');
                const mm = date.getMinutes().toString().padStart(2, '0');
                const ss = date.getSeconds().toString().padStart(2, '0');
                formattedDate += ` ${HH}:${mm}:${ss}`;
            }

            return formattedDate;
        },

        addList(index) {
            let time = this.ruleForm.addList[index].dutyDate;
            let dutyDate = ''
            if (time) {
                let date = this.getNextDay(new Date(time));
                dutyDate = this.formatDate(date)
            }
            this.$set(this.ruleForm.addList, index + 1, {
                driver: [],
                officer: [],
                leader: [],
                dutyDate: dutyDate
            })
        },
        delList(index) {
            let list = this.ruleForm.addList;
            list = list.splice(index, 1)
            this.$set(this.ruleForm, addList, list)
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let paramsList = []
                    if (this.addEditFlag == 'edit') {
                        paramsList = [this.ruleForm]
                    } else {
                        paramsList = this.ruleForm.addList
                        console.log(this.ruleForm.addList)
                    }
                    paramsList = paramsList.filter(item => {
                        if (item.driver.length > 0 || item.officer.length > 0 || item.leader.length > 0) {
                            return true
                        } else {
                            return false
                        }
                    })
                    paramsList = paramsList.map(item => {
                        return {
                            ...item,
                            driver: item.driver.join(','),
                            officer: item.officer.join(','),
                            leader: item.leader.join(',')
                        }
                    })
                    if (this.addEditFlag == 'add') {
                        if (paramsList.length == 0) {
                            this.$message.warning('请完善信息')
                            return
                        }
                        this.addEditApi(paramsList).then(res => {
                            let success = res.code == 0
                            let msg = success ? '操作成功' : '操作失败'
                            this.$message[success ? 'success' : 'warning'](res.msg || msg)
                            success && this.cancel();
                        }).catch(err => {
                            console.log(err)
                        })
                    } else {
                        this.addEditApi({
                            ...this.ruleForm,
                            driver: this.ruleForm.driver.join(','),
                            officer: this.ruleForm.officer.join(','),
                            leader: this.ruleForm.leader.join(',')
                        }).then(res => {
                            let success = res.code == 0
                            let msg = success ? '操作成功' : '操作失败'
                            this.$message[success ? 'success' : 'warning'](res.msg || msg)
                            success && this.cancel();
                        }).catch(err => {
                            console.log(err)
                        })
                    }
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.fileIdList = [];
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.elRowLine {
    border-bottom: 1px dashed #cecece8a;
    margin-bottom: 20px;
}
</style>